/* eslint-disable */
import { login, changePassword } from '@/request/api'
import { listLeftGet, getLeftList } from '@/request/system/administrators'
import { setCookie, getCookie } from '@/utils/utils'
import { editPassword, editPasswordJson } from '@/request/systemManagement/sysuser'
// import tagViews from './tagViews'
let map = new Map()
let LOCAL_MENUS = []
try {
  let menus = JSON.parse(localStorage.getItem('MENUS_DX'))
  LOCAL_MENUS = menus || []
} catch (e) {
  console.log('local menus does not exist')
}
const state = {
  showDiv: false,
  Grandson: [],
  permList: [],
  ROLE_TYPE_DX_H: getCookie('ROLE_TYPE_DX_H'),
  DPTID_DX_H: getCookie('DPTID_DX_H'),
  FLT_UUID_DX_H: getCookie('FLT_UUID_DX_H'),
  UserId_DX_H: getCookie('UserId_DX_H'),
  FLT_NAME_DX_H: getCookie('FLT_NAME_DX_H'),
  USR_CODE_DX_H: getCookie('USR_CODE_DX_H'),
  USR_RLES_DX_H: getCookie('USR_RLES_DX_H'),
  USERNAME_DX_H: getCookie('USERNAME_DX_H'), // 用户名

  Session_Token: getCookie('Session_Token'),
  // SessionId: getLoginCookie('SessionId'),
  // FLT_UUID: getLoginCookie('FLT_UUID'), // 企业代码
  // UserId: getLoginCookie('UserId'),
  passwordPageStatus: false, // 修改密码页面的是否打开的状态
  MENUS: LOCAL_MENUS,
  navButtonItem: {},
  navListItem: [],
  navTiaoItem: []
}

const getters = {
  // doneTodosCount: (state, getters) => {
  //   return state.Grandson
  // }
  AUTH_URL: state => {
    let res = {}
    state.MENUS.forEach(item => {
      let url = `/layout${item.url}`
      res[url] = item.codeList
    })
    return res
  },
  //左边列表数据
  GET_NAV_BUTTON: state => {
    return state.navButtonItem
  },
  //点击面包屑数据
  // GET_NAV_TIAO: state => {
  //   return state.navTiaoItem;
  //  },
  GET_NAV_LIST_ITEM: state => {
    return state.navListItem
  }
}

const mutations = {
  SET_COOKIE(state, UserInfo) {
    state.ROLE_TYPE_DX_H = UserInfo.roleType
    state.FLT_NAME_DX_H = UserInfo.fltName
    state.FLT_UUID_DX_H = UserInfo.fltId
    state.DPTID_DX_H = UserInfo.dptId
    state.USERNAME_DX_H = UserInfo.userName
    state.USR_CODE_DX_H = UserInfo.userCode
    state.USR_RLES_DX_H = UserInfo.userRoles
    state.UserId_DX_H = UserInfo.userId

    state.Session_Token = UserInfo.sessionId
    setCookie('ROLE_TYPE_DX_H', UserInfo.roleType)
    setCookie('FLT_NAME_DX_H', UserInfo.fltName)
    setCookie('DPTID_DX_H', UserInfo.dptId)
    setCookie('FLT_UUID_DX_H', UserInfo.fltId)
    setCookie('USERNAME_DX_H', UserInfo.userName)
    setCookie('USR_CODE_DX_H', UserInfo.userCode)
    setCookie('USR_RLES_DX_H', UserInfo.userRoles)
    setCookie('UserId_DX_H', UserInfo.userId)

    setCookie('Session_Token', UserInfo.sessionId)
    // setCookie('cookiestest', 'SessionId=4474bd77ca0e49af9977448ac5c143d4&UserId=FC652E7AA1BA4EB1AC82308DE5D85340&UserCode=CSUSER&FLT_UUID=B1C25689738A41B2982B37C714B5C4F0')
  },
  SET_PASSWORD_PAGE_STATUS(state, status) {
    state.passwordPageStatus = status
  },
  REMOVE_ALL_COOKIES(state) {
    state.ROLE_TYPE_DX_H = ''
    state.FLT_NAME_DX_H = ''
    state.FLT_UUID_DX_H = ''
    state.DPTID_DX_H = ''
    state.USERNAME_DX_H = ''
    state.USR_CODE_DX_H = ''
    state.USR_RLES_DX_H = ''
    state.UserId_DX_H = ''
    state.Session_Token = ''
    setCookie('ROLE_TYPE_DX_H', '')
    setCookie('USERNAME_DX_H', '')
    setCookie('FLT_UUID_DX_H', '')
    setCookie('DPTID_DX_H', '')
    setCookie('USERNAME_DX_H', '')
    setCookie('USR_CODE_DX_H', '')
    setCookie('USR_RLES_DX_H', '')
    setCookie('UserId_DX_H', '')
    setCookie('Session_Token', '')
  },
  BUT_PER(state, UserInfo) {
    state.Grandson = UserInfo
  },
  PERM_LIST(state, UserInfo) {
    state.permList = UserInfo
  },
  IS_SHOW(state, showDiv) {
    state.showDiv = showDiv
  },
  GET_MENU(state, menus) {
    state.MENUS = menus
    localStorage.setItem('MENUS_DX', JSON.stringify(menus))
  },
  //设置循环添加按钮
  SET_NAV_BUTTON(state, item) {
    state.navButtonItem = {}
    state.navButtonItem = item
    //判断navListItem数组是否为空
    if (state.navListItem.length > 0) {
      // 限制navListItem数组 find对比navButtonItem数组的数据跟navListItem里的数据是否相同，有相同数据则不添加到navListItem空数组，
      const _item = state.navListItem.find(e => {
        return e.mdlId === item.mdlId
      })
      !_item ? state.navListItem.push(item) : null
    } else {
      // 没有相同数据则添加到navListItem空数组
      state.navListItem.push(item)
    }
  }
  // SET_NAV_TIAO(state,item){
  //   // console.log(item,88888)
  //   state.navTiaoItem = [];
  //   state.navTiaoItem = item;
  // }
}
const actions = {
  // set password page status
  setPasswordPageStatus({ commit, state }, status) {
    return new Promise((resolve, reject) => {
      commit('SET_PASSWORD_PAGE_STATUS', status)
      resolve(state.passwordPageStatus)
    })
  },

  is_show({ commit, state }, showDiv) {
    return new Promise(resolve => {
      commit('IS_SHOW', showDiv)
      resolve(state.showDiv)
    })
  },
  // 登录
  logIn({ commit, dispatch }, userInfo) {
    return new Promise((resolve, reject) => {
      // 周普接口测试 poolLogin(userInfo).then((response) => {
      login(userInfo)
        .then(response => {
          if (response.data.roleType == '') {
            localStorage.setItem('IS_SHOW1', 1)
            // window._I18N_.zh.router.Statement = ''
          }
          if (response.data.roleType == 'c') {
            // window._I18N_.zh.router.Statement = '集团首页'
            localStorage.setItem('IS_SHOW1', 2)
          }
          if (response.data.roleType == 'h') {
            // window._I18N_.zh.router.Statement = '货主首页'
            localStorage.setItem('IS_SHOW1', 3)
          }

          if (response.data.roleType == 'g') {
            // window._I18N_.zh.router.Statement = '供应商首页'
            localStorage.setItem('IS_SHOW1', 4)
          }
          if (response.data.roleType == 'p') {
            // window._I18N_.zh.router.Statement = '平台首页'
            localStorage.setItem('IS_SHOW1', 5)
          }
          if (response.data.roleType == 'j') {
            // window._I18N_.zh.router.Statement = '糖厂首页'
            localStorage.setItem('IS_SHOW1', 6)
          }
          if (response.success == '1') {
            commit('SET_COOKIE', response.data)
            commit('IS_SHOW', false)
            resolve()
            // return
          } else if (response.success == '10086') {
            commit('IS_SHOW', true)
            reject()
          } else {
            if (response.success == '0') {
              let err = new Error()
              err.message = response.msg
              reject(err)
              // return
            } else {
              let err = new Error()
              err.message = '登录失败，请核对后再登录'
              reject(err)
              // return
              // this.$message.warning({message: '登录失败，请核对后再登录！'})
            }
          }

          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 登出
  logOut({ commit }) {
    return new Promise((resolve, reject) => {
      commit('REMOVE_ALL_COOKIES')
      // 清除tagViews
      commit(
        'tagViews/DEL_ALL_TAGS',
        {},
        {
          root: true
        }
      )
      resolve()
      // logout(state.SessionId).then(() => {
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // 获取左边菜单以及页面中的按钮权限
  listLeftGet({ commit }) {
    return new Promise((resolve, reject) => {
      listLeftGet()
        .then(res => {
          commit('GET_MENU', res.data)
          resolve()
        })
        .catch(err => {
          reject(err)
        })
    })
  },

  //按钮权限
  buttonPerm({ commit, dispatch }, userInfo) {
    // new Promise((resolve, reject)=>{
    commit('BUT_PER', userInfo)
    // console.log('userInfo',userInfo)
    //   resolve(state.Grandson)
    // })
  },
  //模块列表
  permList({ commit, dispatch }, userInfo) {
    commit('PERM_LIST', userInfo)
  },
  // permList({
  //   commit
  // }) {
  //   return new Promise((resolve, reject) => {
  //     getLeftList().then(res => {
  //       commit('PERM_LIST', res.data)
  //       resolve()
  //     }).catch(err => {
  //       reject(err)
  //     })

  //   })
  // },
  // 修改密码
  changePassword({ commit, state }, changePwdFormData) {
    var data = {
      uuid: changePwdFormData.username,
      old: changePwdFormData.password,
      password: changePwdFormData.newPassword
    }
    return new Promise((resolve, reject) => {
      editPasswordJson(JSON.stringify(data))
        .then(response => {
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
